<?php
namespace app\api\controller;

use think\Db;
use think\Exception;

class Search extends BaseController
{
    /**
     * 综合搜索
     */
    public function search()
    {
        $keyword = input('keyword/s', '');
        $type = input('type/s', 'all'); // all, parking, activity, news, help
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        if (empty($keyword)) {
            return $this->renderError('搜索关键词不能为空');
        }
        
        // 记录搜索日志
        $this->logSearch($keyword, $type);
        
        try {
            $result = [];
            
            switch ($type) {
                case 'parking':
                    $result = $this->searchParking($keyword, $page, $limit);
                    break;
                case 'activity':
                    $result = $this->searchActivity($keyword, $page, $limit);
                    break;
                case 'news':
                    $result = $this->searchNews($keyword, $page, $limit);
                    break;
                case 'help':
                    $result = $this->searchHelp($keyword, $page, $limit);
                    break;
                case 'all':
                default:
                    $result = $this->searchAll($keyword, $page, $limit);
                    break;
            }
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('搜索失败：' . $e->getMessage());
        }
    }
    
    /**
     * 搜索停车场
     */
    private function searchParking($keyword, $page, $limit)
    {
        $parking_lots = Db::name('parking_lots')
            ->where('status', 1)
            ->where('name|address|description', 'like', '%' . $keyword . '%')
            ->field('lot_id, name, address, total_spaces, available_spaces, hourly_rate, latitude, longitude, description')
            ->order('name asc')
            ->paginate($limit, false, ['page' => $page]);
        
        return [
            'type' => 'parking',
            'data' => $parking_lots->items(),
            'total' => $parking_lots->total(),
            'page' => $page,
            'limit' => $limit,
            'pages' => $parking_lots->lastPage()
        ];
    }
    
    /**
     * 搜索活动
     */
    private function searchActivity($keyword, $page, $limit)
    {
        $activities = Db::name('activities')
            ->where('status', 1)
            ->where('title|description|content', 'like', '%' . $keyword . '%')
            ->field('activity_id, title, description, start_time, end_time, max_participants, current_participants, activity_type, cover_image')
            ->order('start_time desc')
            ->paginate($limit, false, ['page' => $page]);
        
        // 处理数据
        $items = $activities->items();
        foreach ($items as &$item) {
            $item['cover_image'] = $item['cover_image'] ? $this->getFullUrl($item['cover_image']) : '';
            $item['start_time_text'] = date('Y-m-d H:i', strtotime($item['start_time']));
            $item['end_time_text'] = date('Y-m-d H:i', strtotime($item['end_time']));
            
            // 判断活动状态
            $now = time();
            $start_time = strtotime($item['start_time']);
            $end_time = strtotime($item['end_time']);
            
            if ($now < $start_time) {
                $item['activity_status'] = 'upcoming';
                $item['activity_status_text'] = '即将开始';
            } elseif ($now >= $start_time && $now <= $end_time) {
                $item['activity_status'] = 'ongoing';
                $item['activity_status_text'] = '进行中';
            } else {
                $item['activity_status'] = 'ended';
                $item['activity_status_text'] = '已结束';
            }
        }
        
        return [
            'type' => 'activity',
            'data' => $items,
            'total' => $activities->total(),
            'page' => $page,
            'limit' => $limit,
            'pages' => $activities->lastPage()
        ];
    }
    
    /**
     * 搜索新闻
     */
    private function searchNews($keyword, $page, $limit)
    {
        $news = Db::name('news')
            ->where('status', 1)
            ->where('title|summary|content', 'like', '%' . $keyword . '%')
            ->field('news_id, title, summary, cover_image, category, view_count, created_at')
            ->order('created_at desc')
            ->paginate($limit, false, ['page' => $page]);
        
        // 处理数据
        $items = $news->items();
        foreach ($items as &$item) {
            $item['cover_image'] = $item['cover_image'] ? $this->getFullUrl($item['cover_image']) : '';
            $item['created_at_text'] = date('Y-m-d H:i', strtotime($item['created_at']));
        }
        
        return [
            'type' => 'news',
            'data' => $items,
            'total' => $news->total(),
            'page' => $page,
            'limit' => $limit,
            'pages' => $news->lastPage()
        ];
    }
    
    /**
     * 搜索帮助文档
     */
    private function searchHelp($keyword, $page, $limit)
    {
        $help_docs = Db::name('help_docs')
            ->where('status', 1)
            ->where('title|summary|content', 'like', '%' . $keyword . '%')
            ->field('doc_id, title, summary, category, view_count, created_at')
            ->order('sort asc, created_at desc')
            ->paginate($limit, false, ['page' => $page]);
        
        // 处理数据
        $items = $help_docs->items();
        foreach ($items as &$item) {
            $item['created_at_text'] = date('Y-m-d H:i', strtotime($item['created_at']));
        }
        
        return [
            'type' => 'help',
            'data' => $items,
            'total' => $help_docs->total(),
            'page' => $page,
            'limit' => $limit,
            'pages' => $help_docs->lastPage()
        ];
    }
    
    /**
     * 综合搜索
     */
    private function searchAll($keyword, $page, $limit)
    {
        $result = [
            'type' => 'all',
            'parking' => [],
            'activity' => [],
            'news' => [],
            'help' => []
        ];
        
        // 搜索停车场（限制3条）
        $parking_result = $this->searchParking($keyword, 1, 3);
        $result['parking'] = $parking_result['data'];
        
        // 搜索活动（限制3条）
        $activity_result = $this->searchActivity($keyword, 1, 3);
        $result['activity'] = $activity_result['data'];
        
        // 搜索新闻（限制3条）
        $news_result = $this->searchNews($keyword, 1, 3);
        $result['news'] = $news_result['data'];
        
        // 搜索帮助文档（限制3条）
        $help_result = $this->searchHelp($keyword, 1, 3);
        $result['help'] = $help_result['data'];
        
        return $result;
    }
    
    /**
     * 获取热门搜索关键词
     */
    public function getHotKeywords()
    {
        $limit = input('limit/d', 10);
        
        try {
            // 获取最近7天的热门搜索词
            $start_time = date('Y-m-d', strtotime('-7 days'));
            
            $hot_keywords = Db::name('search_log')
                ->where('created_at', '>=', $start_time)
                ->field('keyword, COUNT(*) as search_count')
                ->group('keyword')
                ->order('search_count desc')
                ->limit($limit)
                ->select();
            
            return $this->renderSuccess($hot_keywords);
        } catch (Exception $e) {
            return $this->renderError('获取热门搜索失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取搜索建议
     */
    public function getSuggestions()
    {
        $keyword = input('keyword/s', '');
        $limit = input('limit/d', 10);
        
        if (empty($keyword)) {
            return $this->renderSuccess([]);
        }
        
        try {
            $suggestions = [];
            
            // 从停车场名称中获取建议
            $parking_suggestions = Db::name('parking_lots')
                ->where('status', 1)
                ->where('name', 'like', $keyword . '%')
                ->field('name as suggestion')
                ->limit(3)
                ->select();
            
            // 从活动标题中获取建议
            $activity_suggestions = Db::name('activities')
                ->where('status', 1)
                ->where('title', 'like', $keyword . '%')
                ->field('title as suggestion')
                ->limit(3)
                ->select();
            
            // 从搜索历史中获取建议
            $history_suggestions = Db::name('search_log')
                ->where('keyword', 'like', $keyword . '%')
                ->field('keyword as suggestion, COUNT(*) as count')
                ->group('keyword')
                ->order('count desc')
                ->limit(4)
                ->select();
            
            // 合并建议
            $all_suggestions = array_merge(
                $parking_suggestions,
                $activity_suggestions,
                $history_suggestions
            );
            
            // 去重并限制数量
            $unique_suggestions = [];
            $seen = [];
            
            foreach ($all_suggestions as $item) {
                $suggestion = $item['suggestion'];
                if (!in_array($suggestion, $seen) && count($unique_suggestions) < $limit) {
                    $unique_suggestions[] = $suggestion;
                    $seen[] = $suggestion;
                }
            }
            
            return $this->renderSuccess($unique_suggestions);
        } catch (Exception $e) {
            return $this->renderError('获取搜索建议失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取搜索历史
     */
    public function getSearchHistory()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $limit = input('limit/d', 20);
        
        try {
            $history = Db::name('search_log')
                ->where('member_id', $member_id)
                ->field('keyword, created_at')
                ->order('created_at desc')
                ->limit($limit)
                ->select();
            
            // 去重
            $unique_history = [];
            $seen = [];
            
            foreach ($history as $item) {
                if (!in_array($item['keyword'], $seen)) {
                    $unique_history[] = $item;
                    $seen[] = $item['keyword'];
                }
            }
            
            return $this->renderSuccess($unique_history);
        } catch (Exception $e) {
            return $this->renderError('获取搜索历史失败：' . $e->getMessage());
        }
    }
    
    /**
     * 清除搜索历史
     */
    public function clearSearchHistory()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        
        try {
            Db::name('search_log')
                ->where('member_id', $member_id)
                ->delete();
            
            return $this->renderSuccess(['message' => '搜索历史已清除']);
        } catch (Exception $e) {
            return $this->renderError('清除搜索历史失败：' . $e->getMessage());
        }
    }
    
    /**
     * 删除单条搜索历史
     */
    public function deleteSearchHistory()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $keyword = input('keyword/s', '');
        
        if (empty($keyword)) {
            return $this->renderError('关键词不能为空');
        }
        
        try {
            Db::name('search_log')
                ->where([
                    'member_id' => $member_id,
                    'keyword' => $keyword
                ])
                ->delete();
            
            return $this->renderSuccess(['message' => '删除成功']);
        } catch (Exception $e) {
            return $this->renderError('删除失败：' . $e->getMessage());
        }
    }
    
    /**
     * 记录搜索日志
     */
    private function logSearch($keyword, $type)
    {
        try {
            $member_id = $this->getUserId() ?? 0;
            
            $data = [
                'member_id' => $member_id,
                'keyword' => $keyword,
                'search_type' => $type,
                'ip_address' => request()->ip(),
                'user_agent' => request()->header('user-agent'),
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            Db::name('search_log')->insert($data);
        } catch (Exception $e) {
            // 记录日志失败不影响搜索功能
        }
    }
    
    /**
     * 获取完整URL
     */
    private function getFullUrl($path)
    {
        if (empty($path)) {
            return '';
        }
        
        if (strpos($path, 'http') === 0) {
            return $path;
        }
        
        return request()->domain() . $path;
    }
}